package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

func main() {
	db, _ := sql.Open(
		"mysql",
		"root:root@tcp(172.20.0.10:3306)/gogogo?charset=utf8&parseTime=true&loc=Local",
	)
	defer db.Close()
	//getOne(db, 1)
	//getList(db)
	getOneWithPrepare(db, 2)
}

func getOne(db *sql.DB, id int) {
	row := db.QueryRow("SELECT * FROM tbl_student WHERE id = ?", id)
	var dbId int
	var stuNo, name string
	var createTime time.Time
	row.Scan(&dbId, &stuNo, &name, &createTime)
	fmt.Printf("id=%d, stuNo=%s, name=%s, createTime=%v\n",
		dbId, stuNo, name, createTime)
}

func getOneWithPrepare(db *sql.DB, id int) {
	stmt, _ := db.Prepare("SELECT * FROM tbl_student WHERE id = ?")
	defer stmt.Close()
	row := stmt.QueryRow(id)
	var dbId int
	var stuNo, name string
	var createTime time.Time
	row.Scan(&dbId, &stuNo, &name, &createTime)
	fmt.Printf("id=%d, stuNo=%s, name=%s, createTime=%v\n",
		dbId, stuNo, name, createTime)
}

func getList(db *sql.DB) {
	rows, err := db.Query("SELECT * from tbl_student")
	if err != nil {
		fmt.Println("error.", err)
	}
	defer rows.Close()
	var id int
	var stuNo, name string
	var createTime time.Time
	for rows.Next() {
		rows.Scan(&id, &stuNo, &name, &createTime)
		fmt.Printf("id=%d, stuNo=%s, name=%s, createTime=%v\n",
			id, stuNo, name, createTime)
	}
}